/*
 * Copyright (C) 2016 The yuhaiyang Android Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package dev.hitools.common.widget.recyclerview.adapter

import android.content.Context
import android.util.SparseArray
import android.view.View
import android.view.ViewGroup
import androidx.core.util.forEach
import androidx.core.util.size
import androidx.recyclerview.widget.RecyclerView
import dev.hitools.common.R
import java.util.*
import kotlin.math.max

/**
 * 封装后的RecycleAdapter
 */
abstract class BaseAdapter<VH : RecyclerView.ViewHolder, T> : RecyclerView.Adapter<VH>() {
    protected lateinit var context: Context

    private var _data: MutableList<T> = ArrayList()
    var data: MutableList<T>?
        get() = _data
        set(data) {
            val lastSize = _data.size
            _data.clear()
            data?.let { _data.addAll(it) }
            notifyItemRangeChanged(0, max(lastSize, _data.size))
        }

    /**
     * Item的点击事件
     */
    private var itemClickListener: OnItemClickListener? = null

    /**
     * 单个View的点击回调事件
     */
    private var childItemClickListener = SparseArray<OnItemChildClickListener>()

    /**
     * 设置itemType的Block
     */
    private var itemTypeBlock: ((position: Int) -> Int)? = null

    override fun onAttachedToRecyclerView(recyclerView: RecyclerView) {
        super.onAttachedToRecyclerView(recyclerView)
        context = recyclerView.context
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): VH {
        val vh = createHolder(parent, viewType)
        setItemListener(vh.itemView)
        setItemChildListener(vh.itemView)
        return vh
    }

    override fun onBindViewHolder(holder: VH, position: Int) {
        holder.itemView.setTag(R.id.tag_position, position)
    }

    /**
     * 用于创建ViewHolder
     */
    abstract fun createHolder(parent: ViewGroup, viewType: Int): VH

    /**
     * 获取ItemView的Type
     */
    override fun getItemViewType(position: Int): Int {
        return if (itemTypeBlock == null) {
            super.getItemViewType(position)
        } else {
            itemTypeBlock!!(position)
        }
    }

    /**
     * 增加数据
     */
    fun plusData(data: T) {
        val lastIndex = _data.size
        _data.add(data)
        notifyItemRangeInserted(lastIndex, 1)
    }

    /**
     * 增加数据
     */
    fun plusData(data: List<T>?) {
        if (data != null) {
            val lastIndex = _data.size
            _data.addAll(data)
            notifyItemRangeInserted(lastIndex, data.size)
        }
    }

    /**
     * 清空数据
     */
    fun clear() {
        val lastSize = _data.size
        _data.clear()
        notifyItemRangeRemoved(0, lastSize)
    }

    /**
     * 获取Item的Count
     */
    override fun getItemCount(): Int = _data.size

    /**
     * 获取某个Item
     */
    fun getItem(position: Int): T = _data[position]

    /**
     * 设置获取ViewType的Block
     */
    @Suppress("unused")
    fun setItemTypeBlock(block: ((Int) -> Int)? = null) {
        itemTypeBlock = block
    }

    /**
     * 设置Item的点击事件
     */
    fun setOnItemClickListener(listener: OnItemClickListener?) {
        itemClickListener = listener
    }

    /**
     * 设置点击Item某个View的点击事件
     */
    fun setOnItemChildClickListener(viewId: Int, listener: OnItemChildClickListener? = null) {
        childItemClickListener.put(viewId, listener)
    }

    /**
     * 内部使用：
     * 设置点击事件
     */
    protected open fun setItemListener(item: View) {
        val listener = itemClickListener ?: return

        item.setOnClickListener {
            val position = item.getTag(R.id.tag_position) as Int
            listener.invoke(position)
        }
    }

    /**
     * 内部使用：
     * 设置点击某个View的点击事件
     */
    protected open fun setItemChildListener(item: View) {
        if (childItemClickListener.size <= 0) {
            return
        }

        childItemClickListener.forEach { key, value ->
            val view: View? = item.findViewById(key)
            view?.setOnClickListener {
                val position = item.getTag(R.id.tag_position) as Int
                value(position, key)
            }
        }
    }

}

/**
 * Item的点击事件
 */
typealias OnItemClickListener = ((position: Int) -> Unit)

/**
 * ItemChild的点击事件
 */
typealias OnItemChildClickListener = ((position: Int, viewId: Int) -> Unit)